{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "d3f6eff1",
   "metadata": {},
   "source": [
    "# 数值训练器"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "bd02fa3a",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pytest\n",
    "import numpy as np\n",
    "\n",
    "import tvm\n",
    "from tvm import relax, TVMError\n",
    "from tvm.relax.training import SetupTrainer, Trainer\n",
    "from tvm.relax.training.optimizer import SGD, Adam\n",
    "from tvm.relax.training.loss import MSELoss\n",
    "from tvm.script import ir as I, relax as R"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "eb22ca22",
   "metadata": {},
   "outputs": [],
   "source": [
    "def _get_backbone():\n",
    "    @I.ir_module\n",
    "    class MLP:\n",
    "        I.module_attrs({\"param_num\": 2, \"state_num\": 0})\n",
    "\n",
    "        @R.function\n",
    "        def backbone(\n",
    "            x: R.Tensor((1, 10), \"float32\"),\n",
    "            w0: R.Tensor((10, 5), \"float32\"),\n",
    "            b0: R.Tensor((5,), \"float32\"),\n",
    "        ):\n",
    "            with R.dataflow():\n",
    "                lv0 = R.matmul(x, w0)\n",
    "                lv1 = R.add(lv0, b0)\n",
    "                out = R.nn.relu(lv1)\n",
    "                R.output(out)\n",
    "            return out\n",
    "\n",
    "    return MLP\n",
    "\n",
    "\n",
    "def _make_dataset():\n",
    "    N = 100\n",
    "    return [[np.ones((1, 10)).astype(np.float32), np.array([[0, 0, 1, 0, 0]], np.float32)]] * N"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b27207d1",
   "metadata": {},
   "source": [
    "## 测试主干网络"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "edff1362",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    },
    "tags": [
     "hide-output"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Name                          Duration (us)  Percent  Device  Count                                      Argument Shapes  \n",
       "vm.builtin.reshape                     2.99     1.27    cpu0      1                                       float32[1, 10]  \n",
       "broadcast_to                           2.43     1.03    cpu0      1                             float32[], float32[1, 5]  \n",
       "multiply                               2.28     0.97    cpu0      3          float32[1, 5], float32[1, 5], float32[1, 5]  \n",
       "where                                  2.19     0.93    cpu0      1  bool[1, 5], float32[], float32[1, 5], float32[1, 5]  \n",
       "vm.builtin.check_tensor_info           2.07     0.88    cpu0      1                                       float32[1, 10]  \n",
       "vm.builtin.match_shape                 1.30     0.55    cpu0      1                                       float32[1, 10]  \n",
       "matmul                                 1.20     0.51    cpu0      1        float32[1, 10], float32[10, 5], float32[1, 5]  \n",
       "vm.builtin.check_tensor_info           1.16     0.49    cpu0      1                                       float32[10, 5]  \n",
       "matmul1                                1.10     0.47    cpu0      1        float32[10, 1], float32[1, 5], float32[10, 5]  \n",
       "vm.builtin.make_tuple                  1.02     0.43    cpu0      1                           float32[10, 5], float32[5]  \n",
       "vm.builtin.make_tuple                  0.97     0.41    cpu0      1                                            float32[]  \n",
       "vm.builtin.match_shape                 0.95     0.40    cpu0      1                                       float32[10, 5]  \n",
       "vm.builtin.match_shape                 0.92     0.39    cpu0      1                                        float32[1, 5]  \n",
       "add                                    0.90     0.39    cpu0      1             float32[1, 5], float32[5], float32[1, 5]  \n",
       "vm.builtin.match_shape                 0.89     0.38    cpu0      1                                           float32[5]  \n",
       "vm.builtin.check_tensor_info           0.89     0.38    cpu0      1                                        float32[1, 5]  \n",
       "collapse_sum                           0.86     0.37    cpu0      1                            float32[1, 5], float32[5]  \n",
       "less                                   0.79     0.33    cpu0      1                            float32[1, 5], bool[1, 5]  \n",
       "add1                                   0.76     0.32    cpu0      1          float32[1, 5], float32[1, 5], float32[1, 5]  \n",
       "subtract                               0.74     0.32    cpu0      1          float32[1, 5], float32[1, 5], float32[1, 5]  \n",
       "relu                                   0.70     0.30    cpu0      1                         float32[1, 5], float32[1, 5]  \n",
       "vm.builtin.check_tensor_info           0.69     0.30    cpu0      1                                           float32[5]  \n",
       "sum                                    0.67     0.29    cpu0      1                             float32[1, 5], float32[]  \n",
       "ones                                   0.56     0.24    cpu0      1                                            float32[]  \n",
       "----------                                                                                                                \n",
       "Sum                                   29.02    12.37             26                                                       \n",
       "Total                                234.51             cpu0      1                                                       \n",
       "\n",
       "Configuration\n",
       "-------------\n",
       "Number of threads: 24\n",
       "Executor: VM"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "backbone = _get_backbone()\n",
    "pred_sinfo = relax.TensorStructInfo((1, 5), \"float32\")\n",
    "target_sinfo = relax.TensorStructInfo((1, 5), \"float32\")\n",
    "\n",
    "setup_trainer = SetupTrainer(\n",
    "    MSELoss(reduction=\"sum\"),\n",
    "    Adam(0.01),\n",
    "    [pred_sinfo, target_sinfo],\n",
    ")\n",
    "\n",
    "target = \"llvm\"\n",
    "dev = tvm.device(target, 0)\n",
    "train_mod = setup_trainer(backbone)\n",
    "ex = tvm.compile(train_mod, target)\n",
    "vm = relax.VirtualMachine(ex, dev, profile=True)\n",
    "\n",
    "trainer = Trainer(train_mod, vm, dev, False)\n",
    "trainer.zero_init_params()\n",
    "trainer.xaiver_uniform_init_params()\n",
    "\n",
    "dataset = _make_dataset()\n",
    "trainer.predict(dataset[0][0])\n",
    "trainer.update(dataset[0][0], dataset[0][1])\n",
    "trainer.profile_adjoint(dataset[0][0], dataset[0][1])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f2aa552b",
   "metadata": {},
   "source": [
    "## 测试数值一致性"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "89797b0d",
   "metadata": {},
   "outputs": [],
   "source": [
    "backbone = _get_backbone()\n",
    "pred_sinfo = relax.TensorStructInfo((1, 5), \"float32\")\n",
    "target_sinfo = relax.TensorStructInfo((1, 5), \"float32\")\n",
    "\n",
    "setup_trainer = SetupTrainer(\n",
    "    MSELoss(reduction=\"sum\"),\n",
    "    SGD(0.01),\n",
    "    [pred_sinfo, target_sinfo],\n",
    ")\n",
    "\n",
    "train_mod = setup_trainer(backbone)\n",
    "ex = tvm.compile(train_mod, target)\n",
    "vm = relax.VirtualMachine(ex, dev)\n",
    "\n",
    "trainer = Trainer(train_mod, vm, dev, False)\n",
    "trainer.zero_init_params()\n",
    "\n",
    "dataset = _make_dataset()\n",
    "for _ in range(2):\n",
    "    for x, label in dataset:\n",
    "        loss = trainer.update(x, label)\n",
    "np.testing.assert_allclose(loss.numpy(), 3.1974423e-14)\n",
    "\n",
    "result = trainer.predict(dataset[0][0])\n",
    "result_expected = np.array([[0, 0, 0.9999998, 0, 0]], np.float32)\n",
    "np.testing.assert_allclose(result.numpy(), result_expected)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "54d959d2",
   "metadata": {},
   "source": [
    "## 加载导出的参数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "5ceee7aa",
   "metadata": {},
   "outputs": [],
   "source": [
    "backbone = _get_backbone()\n",
    "pred_sinfo = relax.TensorStructInfo((1, 5), \"float32\")\n",
    "target_sinfo = relax.TensorStructInfo((1, 5), \"float32\")\n",
    "\n",
    "setup_trainer = SetupTrainer(\n",
    "    MSELoss(reduction=\"sum\"),\n",
    "    SGD(0.01),\n",
    "    [pred_sinfo, target_sinfo],\n",
    ")\n",
    "\n",
    "train_mod = setup_trainer(backbone)\n",
    "ex = tvm.compile(train_mod, target)\n",
    "vm = relax.VirtualMachine(ex, dev)\n",
    "\n",
    "trainer = Trainer(train_mod, vm, dev, False)\n",
    "trainer.xaiver_uniform_init_params()\n",
    "\n",
    "dataset = _make_dataset()\n",
    "for input, label in dataset:\n",
    "    trainer.update(input, label)\n",
    "\n",
    "param_dict = trainer.export_params()\n",
    "assert \"w0\" in param_dict\n",
    "assert \"b0\" in param_dict\n",
    "\n",
    "trainer1 = Trainer(train_mod, vm, dev, False)\n",
    "trainer1.load_params(param_dict)\n",
    "\n",
    "x_sample = dataset[np.random.randint(len(dataset))][0]\n",
    "np.testing.assert_allclose(\n",
    "    trainer.predict(x_sample).numpy(), trainer1.predict(x_sample).numpy()\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fe5203ef",
   "metadata": {},
   "source": [
    "## 测试设置错误"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "81f68ffc",
   "metadata": {},
   "outputs": [],
   "source": [
    "backbone = _get_backbone()\n",
    "pred_sinfo = relax.TensorStructInfo((1, 5), \"float32\")\n",
    "target_sinfo = relax.TensorStructInfo((1, 5), \"float32\")\n",
    "\n",
    "setup_trainer = SetupTrainer(\n",
    "    MSELoss(reduction=\"sum\"),\n",
    "    SGD(0.01),\n",
    "    [pred_sinfo, target_sinfo],\n",
    ")\n",
    "\n",
    "train_mod = setup_trainer(backbone)\n",
    "ex = tvm.compile(train_mod, target)\n",
    "vm = relax.VirtualMachine(ex, dev)\n",
    "\n",
    "trainer = Trainer(train_mod, vm, dev, False)\n",
    "\n",
    "dataset = _make_dataset()\n",
    "# parameters are not inited\n",
    "with pytest.raises(TVMError):\n",
    "    trainer.predict(dataset[0][0])\n",
    "with pytest.raises(TVMError):\n",
    "    trainer.update(dataset[0][0], dataset[0][1])\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0a0a3e1c",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "ai",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
